package com.aizuda.trans.service.impl.defaults;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.aizuda.trans.annotation.Translate;
import com.aizuda.trans.desensitized.IDesensitized;
import com.aizuda.trans.enums.FormatType;
import com.aizuda.trans.service.WriteFieldNameService;
import com.aizuda.trans.summary.ISummaryExtract;
import com.aizuda.trans.util.NameUtil;

import java.util.List;

/**
 * 默认写入字段名称服务实现
 *
 * @author nn200433
 * @date 2024-01-29 02:04:36
 */
public class DefaultWriteFieldNameServiceImpl implements WriteFieldNameService {

    @Override
    public List<String> getFieldNameList(Translate translateConfig, String originFieldName,
                                         FormatType fieldFormatType) {
        return NameUtil.parseCamelTo(getTranslateFieldName(translateConfig, originFieldName), fieldFormatType);
    }

    /**
     * 若注解中未配置translateField，则默认将原属性名的Id或Code字样替换成Name
     * <p>
     * 如： resTypeId / resTypeCode -> staffName
     *
     * @param translateConfig 转换配置
     * @param originFieldName 原始字段名称
     * @return {@link List }<{@link String }>
     * @author nn200433
     */
    private List<String> getTranslateFieldName(Translate translateConfig, String originFieldName) {
        final Class<?> dictClass           = translateConfig.dictClass();
        final String   newName             = originFieldName.replaceFirst("(Id|Code)$|$", "Name");
        String[]       translateFieldArray = translateConfig.translateField();
        final int      translateFieldLen   = translateFieldArray.length;
        if (translateFieldLen == 0) {
            if (IDesensitized.class.isAssignableFrom(dictClass) || ISummaryExtract.class.isAssignableFrom(dictClass)) {
                // 脱敏与摘要提取功能，没配置翻译字段，直接返回原字段（即替换原始数据）
                translateFieldArray = new String[]{originFieldName};
            } else {
                // 否则返回额外提供的翻译字段
                translateFieldArray = new String[]{newName};
            }
        } else {
            for (int i = 0; i < translateFieldLen; i++) {
                final String translateField = translateFieldArray[i];
                if (StrUtil.isBlank(translateField)) {
                    translateFieldArray[i] = newName + i;
                }
            }
        }
        return CollUtil.newArrayList(translateFieldArray);
    }

}
